package dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhang.gmall.beans.UniqueVisitStats;
import com.zhang.gmall.utils.KafkaUtil;
import com.zhang.gmall.utils.MyEnv;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * @title: uv统计分析(偏底层算子计算)
 * @author: zhang
 * @date: 2022/3/27 14:12
 */
@Deprecated
public class UniqueVisit10sAppWithProcess {
    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = MyEnv.getStreamingEnv(4, false);

        //TODO 2.从kafka读取页面日志数据,转换结构，分配水位线和提取时间戳
        String sourceTopic = "dwd_page_log";
        String groupId = "unique_visit_10s_app_210927";
        SingleOutputStreamOperator<JSONObject> pageLogWMDS = env
                .addSource(KafkaUtil.getKafkaSource(sourceTopic, groupId))
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSON.parseObject(value);
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                        return element.getLong("ts");
                                    }
                                })
                );

        //TODO 3.按照mid分组，使用状态编程方式计算uv
        SingleOutputStreamOperator<UniqueVisitStats> uvDS = pageLogWMDS
                .keyBy(json -> json.getJSONObject("common").getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, UniqueVisitStats>() {

                    //定义状态变量存储当日内用户访问时间
                    private ValueState<String> firstTimeState;
                    //定义时间格式化
                    private SimpleDateFormat sdf;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("first-time-state", Types.STRING);
                        StateTtlConfig stateTtlConfig = new StateTtlConfig.Builder(Time.days(1))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();
                        valueStateDescriptor.enableTimeToLive(stateTtlConfig);
                        firstTimeState = getRuntimeContext().getState(valueStateDescriptor);

                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }

                    @Override
                    public void processElement(JSONObject logJson, KeyedProcessFunction<String, JSONObject, UniqueVisitStats>.Context ctx, Collector<UniqueVisitStats> out) throws Exception {
                        //用户第一次来到页面记录下来，其他的访问不记录
                        JSONObject pageLogJson = logJson.getJSONObject("page");
                        String lastPageId = pageLogJson.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() <= 0) {
                            Long ts = logJson.getLong("ts");
                            String curTime = sdf.format(new Date(ts));
                            //如果状态为null或者状态时间与当前时间不同,则保留数据,反之过滤掉
                            if (firstTimeState.value() == null || !curTime.equals(firstTimeState.value())) {
                                firstTimeState.update(curTime);
                                JSONObject common = logJson.getJSONObject("common");
                                out.collect(new UniqueVisitStats(
                                        "", "",
                                        common.getString("vc"),
                                        common.getString("ch"),
                                        common.getString("ar"),
                                        common.getString("is_new"),
                                        1L,
                                        ts
                                ));
                            }
                        }
                    }
                });

        //TODO 4.按照4个维度分组进行uv统计
        SingleOutputStreamOperator<UniqueVisitStats> uvStatsDS = uvDS
                .keyBy(new KeySelector<UniqueVisitStats, Tuple4<String, String, String, String>>() {
                    @Override
                    public Tuple4<String, String, String, String> getKey(UniqueVisitStats value) throws Exception {
                        return Tuple4.of(
                                value.getAr(),
                                value.getCh(),
                                value.getIs_new(),
                                value.getVc()
                        );
                    }
                })
                .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .aggregate(new AggregateFunction<UniqueVisitStats, UniqueVisitStats, UniqueVisitStats>() {
                               @Override
                               public UniqueVisitStats createAccumulator() {
                                   return new UniqueVisitStats();
                               }

                               @Override
                               public UniqueVisitStats add(UniqueVisitStats value, UniqueVisitStats accumulator) {
                                   return new UniqueVisitStats(
                                           value.getStt(),
                                           value.getEdt(),
                                           value.getVc(),
                                           value.getCh(),
                                           value.getAr(),
                                           value.getIs_new(),
                                           value.getUv_ct() + accumulator.getUv_ct(),
                                           value.getTs()
                                   );
                               }

                               @Override
                               public UniqueVisitStats getResult(UniqueVisitStats accumulator) {
                                   return accumulator;
                               }

                               @Override
                               public UniqueVisitStats merge(UniqueVisitStats a, UniqueVisitStats b) {
                                   return null;
                               }
                           }
                        , new ProcessWindowFunction<UniqueVisitStats, UniqueVisitStats, Tuple4<String, String, String, String>, TimeWindow>() {
                            @Override
                            public void process(Tuple4<String, String, String, String> stringStringStringStringTuple4, ProcessWindowFunction<UniqueVisitStats, UniqueVisitStats, Tuple4<String, String, String, String>, TimeWindow>.Context context, Iterable<UniqueVisitStats> elements, Collector<UniqueVisitStats> out) throws Exception {
                                //获取数据
                                UniqueVisitStats uniqueVisitStats = elements.iterator().next();

                                //补充窗口信息
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                uniqueVisitStats.setStt(sdf.format(context.window().getStart()));
                                uniqueVisitStats.setEdt(sdf.format(context.window().getEnd()));
                                out.collect(uniqueVisitStats);
                            }
                        }

                );

        //TODO 5.打印测试
        uvStatsDS.print();

        //TODO  执行任务
        env.execute();
    }
}
